package json;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.stream.Collectors;

/**
 * @author Sai
 * Created by Sai on 2019-03-15.
 */
@WebServlet(urlPatterns = {"/json"})
public class JsonServlet extends HttpServlet {
    private static final String URL = "jdbc:h2:d:/test;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String NAME = "sa";
    private static final String PASSWORD = "sa";

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {

            Statement stmt = conn.createStatement();
            Jsonb jsonb = JsonbBuilder.create();

            String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                    .lines().collect(Collectors.joining(System.lineSeparator()));

            // 利用jsonb把json字符串转换为对象
            student s = jsonb.fromJson(postJsonString, student.class);

            stmt.executeUpdate(
                    "CREATE TABLE IF NOT EXISTS `user` (" +
                            "  `id` int(100) unsigned NOT NULL AUTO_INCREMENT," +
                            "  `name` varchar(100) NOT NULL," +
                            "  `identity` varchar(100) NOT NULL," +
                            "  PRIMARY KEY (`id`)" +
                            ");"
            );

            PreparedStatement preparedStatement = conn.prepareStatement("insert into `user` (id,name,identity ) values (?,?,?);");
            preparedStatement.setInt(1, s.getId());
            preparedStatement.setString(2, s.getName());
            preparedStatement.setString(3, s.getIdentity());
            preparedStatement.execute();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        String str = "{\"code\":0,\"msg\":\"操作成功\"}";
        try {
            JSONObject jsonObj = (JSONObject) (new JSONParser().parse(str));
            resp.getWriter().println(jsonObj.toJSONString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 把获取的字符串原样返回
    }
}
